<?php

namespace app\health\job;

use app\health\model\HealthPopularize;
use app\health\model\healthPro\UserData;
use app\health\model\HealthUserChannel;
use app\health\service\MobileHomePlaceService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\queue\Job;

class UserChannelJob extends BaseJob
{

    /**
     * 用户注册渠道记录队列
     * @param Job $job
     * @param [type] $data
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @Author 张旭鹏
     * @DateTime 2023-07-12
     */
    public function fire(Job $job, $data)
    {
        $job->delete();
        if (!empty($data['user'])) {
            echo ('用户ID:' . $data['user']['id'] ?? '') . PHP_EOL;
            echo ('注册IP:' . $data['register_ip'] ?? '') . PHP_EOL;
            echo ('用户小程序场景值:' . $data['channel_data']['scene'] ?? '') . PHP_EOL;
            echo ('来源渠道:' . $data['channel_data']['platform'] ?? '') . PHP_EOL;
            echo ('渠道ID:' . $data['channel_data']['channel_id'] ?? '') . PHP_EOL;
            $healthUserChannel = HealthUserChannel::where('user_id', $data['user']['id'])->find();
            if (!$healthUserChannel) {
                // 查询手机归属地
                $mobileHomePlace = MobileHomePlaceService::inquire($data['user']['mobile']);
                $channel         = [];
                if (!empty($data['channel_data']['channel_id'])) {
                    $channel = HealthPopularize::where('id', $data['channel_data']['channel_id'])->find();
                }
                // 查询用户权益办理数据
                $userData = UserData::where('mobile', $data['user']['mobile'])->order('id', 'desc')->find();
                $pid      = $userData['pid'] ?? 0;
                $zfCode   = $userData['bus_code'] ?? '';
                if (!$pid) {
                    $pid = $channel['pid'] ?? 0;
                }
                if (!$zfCode) {
                    $zfCode = $channel['zf_code'] ?? '';
                }
                HealthUserChannel::create([
                    'user_id'         => $data['user']['id'],
                    'channel_id'      => $channel['id'] ?? 0,
                    'pid'             => $pid,
                    'zf_code'         => $zfCode,
                    'mobile'          => $data['user']['mobile'],
                    'isp'             => $mobileHomePlace['isp'] ?? '',
                    'province'        => $mobileHomePlace['province'] ?? '',
                    'city'            => $mobileHomePlace['city'] ?? '',
                    'city_cde'        => $mobileHomePlace['zone_code'] ?? '',
                    'register_ip'     => $data['register_ip'] ?? '',
                    'scene'           => $data['channel_data']['scene'] ?? '',
                    'source_platform' => $data['channel_data']['platform'] ?? '',
                ]);
            }
        }
    }
}
